package com.cloudcc.mobile;

import java.lang.Thread.UncaughtExceptionHandler;

import com.cloudcc.mobile.manager.RunTimeManager;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Looper;
import android.widget.Toast;


/**
 * @Description: APP异常管理器
 * @author wangzhiqiang
 * @date 2015-11-10 上午11:13:45
 * 
 */
public class AppException implements UncaughtExceptionHandler {
	private UncaughtExceptionHandler mDefaultHandler;
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private AppException() {
		this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
	}

	/**
	 * 获取 异常处理期
	 * 
	 * @return
	 */
	public static AppException getAppExceptionHandler() {
		return new AppException();
	}

	/**
	 * 初始化
	 */
	public static void init() {
		Thread.setDefaultUncaughtExceptionHandler(getAppExceptionHandler());
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		if (!handleException(ex) && mDefaultHandler != null) {
			mDefaultHandler.uncaughtException(thread, ex);
		}
	}

	private boolean handleException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		new Thread() {
			public void run() {
				Looper.prepare();
//				if("en".equals(mEns)){
//					Toast.makeText(AppContext.getInstance(),
//							"Dear, sorry, the application has an exception, will exit..", 1).show();
//				}else{
//
//				}
				Toast.makeText(AppContext.getInstance(),AppContext.getInstance().getResources().getString(R.string.benkuis), 1).show();
//				Toast.makeText(AppContext.getInstance(),ex.getMessage(), 1).show();
				Looper.loop();
			}
		}.start();

		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 退出程序
		AppManager.getInstance().AppExit();
		ActivityManager activityMgr = (ActivityManager) AppContext
				.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
		activityMgr.killBackgroundProcesses(AppContext.getInstance()
				.getPackageName());
		System.exit(0);
		return true;
	}

}
